package com.woniu.service.idiom.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.woniu.entity.idiom.IdiomExamEntity;
import com.woniu.entity.idiom.IdiomRedBeansRecEntity;
import com.woniu.mapper.idiom.IdiomExamMapper;
import com.woniu.service.idiom.IdiomExamService;
import com.woniu.service.idiom.IdiomRedBeansRecService;
import com.woniu.utils.RedisUtil;
import com.woniu.utils.TokenUtil;
import com.woniu.vo.idiom.ExamAnswerVo;
import com.woniu.vo.idiom.IdiomExamAnswerReq;
import com.woniu.vo.idiom.IdiomExamAnswerResp;
import com.woniu.vo.idiom.IdiomExamDetailResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("idiomExamService")
public class IdiomExamServiceImpl extends ServiceImpl<IdiomExamMapper, IdiomExamEntity> implements IdiomExamService {
    private final static Logger logger = LoggerFactory.getLogger(IdiomExamServiceImpl.class);

    private final static String MAIN_TITLEA = "恭喜你，获得红豆";

    private final static String SECONDARY_TITLEA = "答对3道题";

    private final static String MAIN_TITLEB = "很遗憾，未获得奖励";

    private final static String SECONDARY_TITLEB = "答错%d道题";

    private final static String ICON = "";

    @Autowired
    private IdiomRedBeansRecService redBeansRecService;

    @Autowired
    private TokenUtil tokenUtil;


    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<IdiomExamDetailResp> getDetailByIdiomId(int id) {
        List<IdiomExamEntity> idiomExamEntityList = this.list(new QueryWrapper<IdiomExamEntity>().eq("idiom_id", id));

        List<IdiomExamDetailResp> respList = Lists.newArrayList();
        for (IdiomExamEntity entity : idiomExamEntityList) {
            IdiomExamDetailResp idiomExamResp = new IdiomExamDetailResp();
            BeanUtils.copyProperties(entity, idiomExamResp);
            idiomExamResp.setIdiomId(entity.getIdiomId());
            respList.add(idiomExamResp);
        }

        logger.info("getDetailByIdiomId detail:{}", JSON.toJSONString(respList));
        return respList;
    }

    @Override
    public IdiomExamAnswerResp answer(IdiomExamAnswerReq idiomExamReq) {
        //String userId = tokenUtil.getUserId();
        String userId = "test";
        SimpleDateFormat temp = new SimpleDateFormat("yyyy-MM-dd");
        String key = "idiom:today:answer:" + temp.format(new Date()) + ":" + userId;


        List<ExamAnswerVo> answerVoList = idiomExamReq.getAnswers();
        int idiomId = idiomExamReq.getIdiomId();
        if (StrUtil.isBlank(redisUtil.getString(key))) {
            Map<Integer, String> map = answerVoList.stream().collect(Collectors.toMap(ExamAnswerVo::getId, ExamAnswerVo::getAnswer));
            //校验答案
            List<IdiomExamEntity> idiomExamEntityList = this.list(new QueryWrapper<IdiomExamEntity>().eq("idiom_id", idiomId));

            boolean flag = true;
            int error = 0;
            for (IdiomExamEntity entity : idiomExamEntityList) {
                String answer = map.get(entity.getId());
                if (!answer.equals(entity.getAnswer())) {
                    flag = false;
                    error++;
                }
            }
            IdiomExamAnswerResp resp = new IdiomExamAnswerResp();
            resp.setHasSuccess(flag ? 1 : 0);
            resp.setCount(10);
            resp.setIcon(ICON);
            if (flag) {
                resp.setMainTitle(MAIN_TITLEA);
                resp.setSecondaryTitle(SECONDARY_TITLEA);
                // 记录表
                IdiomRedBeansRecEntity entity = new IdiomRedBeansRecEntity();
                entity.setBeansCount(10);
                entity.setUid(userId);
                entity.setType("学习成语，答题成功");
                redBeansRecService.save(entity);
                //写缓存

                redisUtil.set(key, "1", 1L, TimeUnit.DAYS);
            } else {
                resp.setMainTitle(MAIN_TITLEB);
                resp.setSecondaryTitle(String.format(SECONDARY_TITLEB, error));
            }
            return resp;
        }
        return null;
    }


    @Override
    public IdiomExamAnswerResp read() {
        String userId = tokenUtil.getUserId();
        SimpleDateFormat temp = new SimpleDateFormat("yyyy-MM-dd");
        String key = "idiom:today:read:" + temp.format(new Date()) + ":" + userId;
        IdiomExamAnswerResp resp = new IdiomExamAnswerResp();
        if (StrUtil.isBlank(redisUtil.getString(key))) {

            resp.setCount(10);
            resp.setIcon(ICON);

            resp.setMainTitle(MAIN_TITLEA);
            resp.setSecondaryTitle("每天阅读一篇文章");
            // 记录表
            IdiomRedBeansRecEntity entity = new IdiomRedBeansRecEntity();
            entity.setBeansCount(10);
            entity.setUid(userId);
            entity.setType("阅读一篇美文");
            redBeansRecService.save(entity);
            //写缓存
            redisUtil.set(key, "1", 1L, TimeUnit.DAYS);
        }
        return resp;
    }
}